package controller.day03;
import com.alibaba.fastjson2.JSON;
import entity.ResultVo;
import entity.User;
import service.UserService;
import service.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 本类用来演示: fastjson工具java对象转换成json字符串
 *
 * @author: success
 * @date: 2022/10/22 2:19 下午
 */
@WebServlet(urlPatterns = "/day03/json")
public class HelloJsonController extends HttpServlet {
    //service层调用mapper层
    //controller层调用service层

    private UserService userService = new UserServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //模拟一条死的数据
        User user = userService.getById(1);
        //2. 定义一个result对象
        ResultVo resultVo = new ResultVo("200","根据id查询",user);
        //目的-> resultVo(java对象)=> json字符串 => 返回到页面中去.

        //1. 设置文档的输出类型
        resp.setContentType("text/json;charset=utf-8");

        //2. 获取文档的输出流
        PrintWriter out = resp.getWriter();

        //java对象转成json字符串
        String resultVoStr = JSON.toJSONString(resultVo);

        //3. 返回出去
        out.print(resultVoStr);
    }
}